package pkg.drowne.org;

import java.util.Timer;
import java.util.TimerTask;
import android.app.Activity;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.Window;
import android.widget.ProgressBar;

public class SpreadTimer extends Activity {
	
	// Preference file
    public static final String PREF_FILE = "pf2";
    private SharedPreferences preferences;
    private boolean clientPlayer = true;
    private int idgame = -1;
	
	TimerTask refreshTask;
	final Handler handler = new Handler();
	Timer t = new Timer();
	
	private ProgressBar prgBar;
	int progress = 0;

	
	@Override
	public void onCreate(Bundle savedInstanceState) {
	  super.onCreate(savedInstanceState);
	 
	  requestWindowFeature(Window.FEATURE_NO_TITLE);
	  
	  setContentView(R.layout.spreadtimer);

	  prgBar = (ProgressBar) findViewById(R.id.spreadtimer_progressbar);
	  prgBar.setProgress(0);
	  prgBar.setMax(60);

	  preferences = getSharedPreferences(PREF_FILE, MODE_PRIVATE);
      idgame = preferences.getInt("idgame", -1);
      clientPlayer = preferences.getBoolean("clientPlayer", true);
      
	  refreshTimer();

	}
    
	public void refreshTimer() {

		refreshTask = new TimerTask() {
			public void run() {
				handler.post(new Runnable() {

					public void run() {
						Log.d("SPREAD TIMER", "SEC " + progress);
					
						progress++;
						
						prgBar.setProgress(progress);
						
						if (prgBar.getProgress() == prgBar.getMax())
							refreshHandler.sendEmptyMessage(1);

					}
				});
			}
		};

		t.schedule(refreshTask, 0, 1000);

	}
    
    private final Handler refreshHandler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			
			if (msg.what == 1) {

			    if(!clientPlayer)
			        Connection.setGamePhase(idgame, Utils.STARTED);
				
				stopRefreshing();
				
				finish();
				
				
			}
		}
	};

    public void stopRefreshing(){

	   if(refreshTask!=null){
	      Log.d("SPREAD TIMER", "CANCELED");
	      refreshTask.cancel();
	      t.cancel();
	      t.purge();
	   }
	   
    }
}
